import $api from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const wx = require('weixin-js-sdk')

const getDefaultState = () => {
  return {
    token: '',
    name: '',
    avatar: '',
  }
}

const state = getDefaultState()

const mutations = {}

const actions = {

  // user login
  login({ state }, userForm) {
    return new Promise((resolve, reject) => {
      $api.login(userForm)
        .then((response) => {
          const { data } = response
          state.token = data.token
          setToken(data.token)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ state }) {
    return new Promise((resolve, reject) => {
      $api.getInfo(state.token)
        .then((res) => {
          const { data } = res

          if (!data) {
            return reject('登录信息获取失败')
          }

          state.userId = data.userId
          state.nickName = data.nickName
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ state }) {
    return new Promise((resolve, reject) => {
      $api.getInfo(state.token)
        .then((res) => {
          const { data } = res

          if (!data) {
            return reject('登录信息获取失败')
          }

          Object.assign(state, getDefaultState())
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  wxConfig({ commit, state }) {
    return new Promise((resolve, reject) => {
      $api.getWxConfig()
        .then((res) => {
          wx.error(function(res) {
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            console.log('wx.error', res)
          })
          wx.config({
            debug: false,
            'appId': res.data.appId,
            'nonceStr': res.data.nonceStr,
            'timestamp': res.data.timestamp,
            'signature': res.data.signature,

            // 必填，需要使用的JS接口列表
            jsApiList: ['scanQRCode'],
          })
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
